import React, { Component } from 'react'
import FreeScrollBar from 'react-free-scrollbar'
import { connect } from 'react-redux'
import { cloneDeep } from 'lodash'
import * as I from '@ant-design/icons'
import { addWindow, addScrollEvent } from '@redux/actions'
import style from './Sider.module.less'
// import { companyName } from '@js/config'
import classNames from 'classnames'
import { $get } from '@src/assets/js/authRequest'
import { awaitWrap } from '@src/assets/js/tool'
import { message } from 'antd'

async function getMeetingUrlRequest () {
  const res = await $get('/api/common/rulefunction/meetinginfo')
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function getMeetingUrl () {
  const h = message.loading('加载中', 0)
  const [e, d] = await awaitWrap(getMeetingUrlRequest())
  h()
  if (e === null && d !== null) {
    window.open(d.url)
  }
}

class Sider extends Component {
  state = {
    menus: [],
    isReady: false,
    top: 0
  }

  // 是否展开菜单
  toggleFirstMenu (index) {
    const menus = this.state.menus.slice()
    const menu = menus[index]
    if (menu.children && menu.children.length > 0) {
      menu.showChildren = !menu.showChildren
      this.setState({
        menus
      })
    } else {
      this.openPage(menu)
    }
  }

  /**
   * 子菜单是否展示中
   */
  isChildrenSelected (list) {
    const goal = list.find(li => li.id === this.props.activeWindowId)
    return goal ? style.active : ''
  }

  /**
   * 从props中拷贝菜单
   */
  cloneMenus () {
    this.setState({
      menus: cloneDeep(this.props.menus)
    })
  }

  /**
   * 打开菜单
   */
  openPage ({ id = '', title = '', componentName = '', closable = true, meta = {}, isHome = false, openurl, openfunction }) {
    if (openurl) {
      if (openurl === 'function') {
        if (openfunction === 'meetinginfo') {
          getMeetingUrl()
        }
      } else {
        window.open(openurl)
      }
    } else {
      this.props.addWindow({ id, title, componentName, closable, meta, isHome })
    }
  }

  /**
   * 渲染菜单列表
   */
  renderMenuList () {
    return this.state.menus.map((menu, i) => {
      let Icon = null
      if (menu.icon) {
        Icon = I[menu.icon]
      }
      return (
        <li key={`${menu.id}-${i}`} className={this.isChildrenSelected(menu.children)}>
          <div className={classNames(style.menu__firstMenu, { [style['no-icon']]: !menu.icon, [style.on]: menu.showChildren })}>
            <div className={style.menu__firstMenu_inner} onClick={() => this.toggleFirstMenu(i)}>
              {Icon ? <div className={style.menu__icon}><Icon /></div> : null}
              <span className={style.firstmenu__title}>{menu.title}</span>
              <div className={style.menu__direction}>
                {this.renderArrow(menu)}
              </div>
            </div>
            {this.renderSubMenu(menu)}
          </div>
        </li>
      )
    })
  }

  // 渲染箭头
  renderArrow (menu) {
    const Arrow = menu.showChildren ? I.UpOutlined : I.DownOutlined
    if (!menu.children.length) {
      return null
    }
    return (
      <Arrow className={style['menu__direction-icon']} />
    )
  }

  // 渲染子菜单
  renderSubMenu (menu) {
    if (menu.showChildren) {
      return (
        <ul className={style['sub-menu']}>
          {this.renderSubMenuList(menu)}
        </ul>
      )
    }
  }

  // 渲染子菜单列表
  renderSubMenuList (menu) {
    return menu.children.map((item, i) => {
      return (
        <li className={classNames({ [style.active]: item.id === this.props.activeWindowId })} key={`${item.id}-${i}`} onClick={() => this.openPage(item)}>
          <span className={style.submenu_title}>{item.title}</span>
        </li>
      )
    })
  }

  initDesktop () {
    // const { windows, userInfo } = this.props
    // const { id, desktop } = userInfo
    // if (id && windows.length === 0) {
    //   this.openPage({ id: '0', title: '桌面', componentName: desktop || 'DefaultDesktop', closable: false, isHome: true })
    // }
    // this.openPage({ id: 'IdcardConfig', title: '读卡器配置', componentName: 'IdcardConfig', meta: { } })
    // this.openPage({ id: '123', title: '仲裁分支机构管理', componentName: 'SubInstitutionManage' })
    // this.openPage({ id: '123', title: '收案', componentName: 'AcceptCase', meta: { id: '1B393BC2ED8A17B37CC91DF4263639C8' } })
  }

  componentDidUpdate (prev) {
    // 当菜单为空时，根据store中的菜单初始化state中的菜单
    const { menus, userInfo, windows } = this.props
    if (prev.menus !== menus) {
      this.cloneMenus()
    }
    if (!prev.userInfo.id && userInfo.id && windows.length === 0) {
      this.initDesktop()
    }
  }

  componentDidMount () {
    this.initDesktop()
    // this.openPage({ id: '4A4039344BFEBAB0CC5068EADD77AEE4', title: '（2025）齐仲字第039号', componentName: 'CaseDetail', meta: { id: '4A4039344BFEBAB0CC5068EADD77AEE4', operate: 'dulizhuanjialunzheng' } })
    this.setState({
      isReady: true
    })
  }

  // 渲染菜单滚动区域
  renderMenus () {
    if (this.state.isReady) {
      return (
        <FreeScrollBar className='mock'>
          <ul className={style.menu}>
            {this.renderMenuList()}
          </ul>
        </FreeScrollBar>
      )
    }
  }

  render () {
    return (
      <div className={style.sider}>
        <div className={style.sider__header}>
          {/* <img src={logo} /> */}
          {/* <h1>{companyName}</h1> */}
        </div>
        <div className={style.sider__content}>
          {this.renderMenus()}
        </div>
      </div>
    )
  }
}

function mapStateToProps (state) {
  return {
    userInfo: state.basic.userInfo,
    menus: state.pageMeta.menus,
    activeWindowId: state.pageMeta.activeWindowId,
    windows: state.pageMeta.windows
  }
}

function mapDispatchToProps (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i)),
    addScrollEvent: (i) => dispatch(addScrollEvent(i))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Sider)
